package cn.lijigou.shopping;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;

import org.json.JSONException;
import org.json.JSONObject;

import com.connect.Constant;
import com.connect.Kaixin;
import com.umeng.api.exp.UMSNSException;
import com.umeng.api.sns.UMSnsService;
import com.umeng.api.sns.UMSnsService.SHARE_TO;


import cn.lijigou.shopping.domain.Image;
import cn.lijigou.shopping.domain.MResult;
import cn.lijigou.shopping.domain.Order;
import cn.lijigou.shopping.domain.Shop;
import cn.lijigou.shopping.domain.User;
import cn.lijigou.shopping.service.MSystem;
import cn.lijigou.shopping.util.GetSingleThreadPool;
import cn.lijigou.shopping.util.Util;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnKeyListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.opengl.Visibility;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Browser;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.StrikethroughSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
/**
 * @author 黄明
 * @version 创建时间：2012-4-6 上午11:30:49 
 * 类说明  关注 今日团购详情页面
 */
public class TodayDetailActivity extends MActivity  implements OnClickListener,OnTouchListener{
	private String pay_tip = "";
	public  String id = "";
	private long time = 0;
	private String phoneNum="";
	private int cpsState=0;
	private String cid ="";
	private Timer timer;
	private TextView back= null;
	private TextView share= null;
	private ViewFlipper viewFlippers;
	private ScrollView scrollViews;
	private ScrollView scrollViewsTwo;
	int x,lastX,init;
	int shopIndex=0;
	ScrollView scrollView;
//	private Drawable sirectDrawable;
	//提供两种ScrollView 1为 2为Two
	private Button register= null;
	private ProgressDialog mProgress = null;
	public  TextView  text_shop_name = null;
	public  TextView  text_pay_price = null;
	public  TextView  text_shop_size = null;
	public  TextView  text_user_name = null;
	public  TextView  text_shop_address = null;
	public  TextView  text_buyTip= null;
	public  TextView  text_shop_mobile = null;
	
	public EditText order_name = null;
	public EditText order_address = null;
	public EditText order_mobile = null;
	public EditText order_size = null;
	
	public TextView payTip = null;
	
//	private LinearLayout bottom_image_ph = null;
//	private LinearLayout bottom_image_map = null;
	private View menu_progressBar;
	
	private Drawable drawable ;
	private ImageView area_img;
	private ProgressBar progressBar;
	private TextView economize;
	private TextView end_time;
//	private TextView expire_time;
	private TextView address;
	private TextView info;
	private TextView notice;
	private TextView source;
	private TextView value;
	private TextView phone;
	private RelativeLayout rl_phone;
	private RelativeLayout rl_address;
	private LinearLayout layout_goods_detail;
	private String url1; 
	public static Button buy;
	private TextView buy_textview;
	
	private ViewPager viewPager;
	private PageAdapter adapter;
	private LayoutInflater mInflater;
	private List<View> mListViews;
	
	
	private ImageView area_imgTwo;
	private ProgressBar progressBarTwo;
	private TextView discountTwo;
	private TextView economizeTwo;
	private TextView end_timeTwo;
	private TextView expire_timeTwo;
	private TextView addressTwo;
	private TextView infoTwo;
	private TextView valueTwo;
	private TextView text_center;
	private RelativeLayout buyTwo;
	private TextView buyTwo_textview;
	private TextView textview_buy_iconTwo;
	
	Button leftButton;
	Button rightButton;
	//用来判断是从哪个页面过来的  shopping过来的为true   订单过来的为false
	private Shop shop;
    private Map<Integer, Drawable> drawableCache=new HashMap<Integer, Drawable>();
	public  final String URL_ACTIVITY_CALLBACK = "weiboandroidsdk://TimeLineActivity";
	public  final String FROM = "xweibo";
    private Order order = null;
//	public static final String appName = "QWeibo4Android";
	public static String shareShopid;
	private String temp2_type = "";
	private String all_flower_data = "";
	
	private byte[] picture;
	private String shareTitle;
	private Shop mShop;
	private TextView discount;
	private ExecutorService executorService = GetSingleThreadPool.getInstance();
	
    private Handler timeHandler = new Handler(){   
    	public void handleMessage(Message msg) {   
    		getQuot();
    	}   
    };   
    public Handler waitHander = new Handler(){   
    	public void handleMessage(Message msg) {  
    		if(msg.what==0){
    			drawable =drawableCache.get(shopIndex);
    			View parent = mListViews.get(shopIndex%8);
    			area_img = (ImageView) parent.findViewById(R.id.area_img);
    			if(drawable!=null){
    				progressBar.setVisibility(View.GONE);
    				area_img.setVisibility(View.VISIBLE);
    				area_img.setMinimumHeight(300);
    				area_img.setImageDrawable(drawable);
    			}else{
    				progressBar.setVisibility(View.GONE);
    				area_img.setVisibility(View.VISIBLE);
    				area_img.setMinimumHeight(300);
    				area_img.setImageResource(R.drawable.load_big);
				
    			}
    		}else if(msg.what==8){
    			menu_progressBar.setVisibility(View.VISIBLE);
    		}else if(msg.what==9){
    			menu_progressBar.setVisibility(View.GONE);
    		}else if(msg.what==7){
    			menu_progressBar.setVisibility(View.GONE);
    		}else if(msg.what==10){
    			adapter.notifyDataSetChanged();
    			if(text_center!=null){
					text_center.setText("团购详情("+(shopIndex+1)+"/"+TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).size()+")");
			  }
    		} 
    	}   
    };   
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.shop_detail);
		overridePendingTransition(R.anim.push_in,R.anim.push_out);
		initButton();
		initDate();
		
		ShopDetailActivity.mList.add(this);
	
	}
	private void initButton() {
		// TODO Auto-generated method stub
		View view=LayoutInflater.from(this).inflate(R.layout.button, null);
		leftButton=(Button)view.findViewById(R.id.left_btn);
		rightButton=(Button)view.findViewById(R.id.right_btn);
		leftButton.setOnClickListener(this);
		rightButton.setOnClickListener(this);
		addContentView(view, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
	}
	private void initDate() {
		// TODO Auto-generated method stub
		setViews();
		Intent intent = getIntent();   
		SharedPreferences preFerence=this.getSharedPreferences("user",MODE_PRIVATE);
		//用来初始提示用户
		int initCode=preFerence.getInt("initCode", 0);
		if(initCode==0){
				Toast.makeText(this,R.string.shopDetail_toast, 1).show();
				preFerence.edit().putInt("initCode", 1).commit();
		}
		 
		temp2_type = intent.getStringExtra("temp2_type");
		all_flower_data = intent.getStringExtra("all_flower_data");
	 
		int  position = this.getIntent().getIntExtra("position", 0);
		shopIndex=position;
		
		adapter = new PageAdapter();
		viewPager = (ViewPager) findViewById(R.id.viewpagerLayout);
		
		mListViews = new ArrayList<View>();
		mInflater = getLayoutInflater();

		for(int i=0;i<8;i++){
			View layout = mInflater.inflate(R.layout.scrollviews, null);
			mListViews.add(layout);
		}
		viewPager.setAdapter(adapter);
		viewPager.setOnPageChangeListener(new OnPageChangeListener()
		{
			
			public void onPageSelected(int position)
			{
				MSystem.detail+=1;
				MSystem.pv+=1;
				if(position<TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).size()){
					if(scrollView!=null){
						  scrollView.post(new Runnable() {
								
								public void run() {
									// TODO Auto-generated method stub
									scrollView.scrollTo(0, 0);
								}
							});
						}
					shopIndex=position;
					if(position==TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).size()-1){
						getShops();
					}
					setDate(TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).get(position),position);
				}
				}
			
			public void onPageScrolled(int arg0, float arg1, int arg2)
			{
			}

			
			public void onPageScrollStateChanged(int arg0)
			{
 
			}
		});
		setDate(TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).get(shopIndex),shopIndex);
		viewPager.setCurrentItem(shopIndex);
		adapter.notifyDataSetChanged();
	}
	private void  setViews(){
		back = (TextView) this.findViewById(R.id.title_btn_left);
		
		share = (TextView) this.findViewById(R.id.title_btn_right);
		share.setText("分享");
		back.setBackgroundResource(R.drawable.title_back_normal);
		findViewById(R.id.titleRightView).setOnClickListener(this);
		this.findViewById(R.id.titleLeftView).setOnClickListener(this);
		
		share.setVisibility(View.VISIBLE);
		
//		bottom_image_ph = (LinearLayout) this.findViewById(R.id.phone);
//		bottom_image_map = (LinearLayout) this.findViewById(R.id.map);
		menu_progressBar = (View) this.findViewById(R.id.menu_progressBar);
		menu_progressBar.setVisibility(View.GONE);
		
		
		text_center=(TextView) this.findViewById(R.id.text_center);
		Intent mIntent = this.getIntent();
	}
	
	String getIdToString(int id){
		String string=this.getResources().getString(id);
		return string;
	}
	
	
 
	private void  setOnClickListeners(){
		buy.setOnClickListener(this);
//		buyTwo.setOnClickListener(this);
		
//		bottom_image_ph.setOnClickListener(this);
//		bottom_image_map.setOnClickListener(this);
		rl_phone.setOnClickListener(this);
		rl_address.setOnClickListener(this);
		layout_goods_detail.setOnClickListener(this);
	}

	public void onClick(View v) {
		MSystem.pv+=1;
		switch (v.getId()) {
		case R.id.rl_phone:
			call();
			break;
		case R.id.rl_address:
			map();
			break;
		case R.id.layout_goods_detail:
			url1 = TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).get(shopIndex).getDetail();
			if(isNull(url1)){
				Intent intent1 = new Intent(TodayDetailActivity.this, GoogsDetailActivity.class);
				intent1.putExtra("url", url1);   
				this.startActivity(intent1);
			}else{
				Toast.makeText(this, "抱歉，本团购暂时还没有详情!", 1).show();
			}
			
			break;
			
			
		case R.id.titleRightView:
			choose_share();
			break;
		case R.id.left_btn:
			if (TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).size() >= shopIndex) {
				if (shopIndex > 0) {
					shopIndex=shopIndex-1;
					setDate(TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).get(shopIndex),shopIndex);
					viewPager.setCurrentItem(shopIndex);
				
				} 
			}
			break;
		case R.id.right_btn:

			if (TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).size() - 1 > shopIndex) {
				shopIndex=shopIndex+1;
				setDate(TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).get(shopIndex),shopIndex);
				viewPager.setCurrentItem(shopIndex);	
			}else{
				
				if(shopIndex==TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).size()-1){
					getShops();
				}
				
			}
			
			break;
		//买的效果实现
		case R.id.buy:
			buy.setEnabled(false);
			mShop = TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).get(shopIndex);
			 //是从类别中进来
			if (cpsState > 0) {
				boolean isCps = MSystem.isCps(cid).isSuccess();
				if (isCps) {
						Intent intent_order = new Intent(TodayDetailActivity.this, OrderApprobateActivity.class);
						mShop.setDrawable(null);
						intent_order.putExtra("shop", mShop);
						TodayDetailActivity.this.startActivity(intent_order);
//					}
				} else {
					Toast.makeText(this, R.string.sorry_tips3, 1).show();
					buy.setEnabled(true);
				}
				
			} else {
					Integer hour = Util.getCurSysTime();
					if (hour >= mShop.getBuy_start_time() && hour < mShop.getBuy_end_time()) {
							Intent intent_order = new Intent(TodayDetailActivity.this, OrderApprobateActivity.class);
							mShop.setDrawable(null);
							intent_order.putExtra("shop", mShop);
							TodayDetailActivity.this.startActivity(intent_order);
					} else {
						// 如果超时 提示用户此时段订单将在第二天处理
						new AlertDialog.Builder(TodayDetailActivity.this)
							.setIcon(R.drawable.icon).setTitle("是否继续购买？")
							.setMessage(mShop.getBuy_end_time() + ":00-" + mShop.getBuy_start_time() + ":00间的订单，我们将在第二天工作时间帮您处理")
							.setPositiveButton(
								R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int whichButton) {
										// 支付
											Intent intent_order = new Intent(TodayDetailActivity.this, OrderApprobateActivity.class);
											mShop.setDrawable(null);
											intent_order.putExtra("shop", mShop);
											TodayDetailActivity.this.startActivity(intent_order);
//										}
									}
								})
							.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) {
									buy.setEnabled(true);
									dialog.dismiss();
								}
						})
						.setOnKeyListener(new OnKeyListener() {
						
						public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
							// TODO Auto-generated method stub
							if (keyCode == KeyEvent.KEYCODE_BACK) {
								buy.setEnabled(true);
								return false;
							}
							return false;
						}
					})
					.create().show();
					}
				}
			
			break;
 
			case R.id.titleLeftView:
				if(timer!=null){
					timer.cancel();
				}
				if(ShopDetailActivity.mList.contains(this)){
					ShopDetailActivity.mList.remove(this);
				}
				this.finish();
				break;
		}
	}
	
	
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			if(v.getId() == buy.getId()){
				buy.setTextColor(Color.WHITE);
				buy.setBackgroundResource(R.drawable.buy_btn_pressed);
			}
			
			break;
		case MotionEvent.ACTION_UP:
			if(v.getId() == buy.getId()){
				buy.setTextColor(Color.BLACK);
				buy.setBackgroundResource(R.drawable.buy_btn_normal);
			}
			break;

		default:
			break;
		}

		return false;
	}
	public void map() {
		if( !isNull(TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).get(shopIndex).getLat()) || TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).get(shopIndex).getLat().equals("0")){
			Toast.makeText(this, "该商户不支持地图服务", 1).show();
		}else{
			if(MSystem.mLocation==null){
				Toast.makeText(this, "尚未知道你的坐标", 1).show();
			}else{
				Intent intent = new Intent(this, MapRoutePlanActivity.class);
				intent.putExtra("city", MSystem.mLocation.city);
				intent.putExtra("start_lat", MSystem.mLocation.getLat());
				intent.putExtra("start_lng", MSystem.mLocation.getLng());
				intent.putExtra("end_lat", Double.parseDouble(TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).get(shopIndex).getLat()));
				intent.putExtra("end_lng", Double.parseDouble(TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).get(shopIndex).getLng()));
				this.startActivity(intent);
			}
		}
	}
	public void call() {
		if(!"".equals(phoneNum)&&phoneNum!=null){
			Uri uri = Uri.parse("tel:"+phoneNum);
		    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		    intent.putExtra(Browser.EXTRA_APPLICATION_ID, this.getPackageName());
		    this.startActivity(intent);
		}else{
			Toast.makeText(this, R.string.not_phone_number, 1).show();
		}
	}

	public void setDate(final Shop shop, int position){
		
		
		
		  View parent = mListViews.get(position%8);
		  scrollView=(ScrollView)parent.findViewById(R.id.scrollViews);
		  buy = (Button) parent.findViewById(R.id.buy);
		  buy.setOnClickListener(this);
		  buy.setOnTouchListener(this);
		  buy_textview = (TextView) parent.findViewById(R.id.textview_buy);
		  area_img = (ImageView) parent.findViewById(R.id.area_img);
		  progressBar = (ProgressBar) parent.findViewById(R.id.progressBar);
		  discount = (TextView) parent.findViewById(R.id.discount);
		  economize = (TextView) parent.findViewById(R.id.economize);
		  end_time = (TextView) parent.findViewById(R.id.end_time);
//		  expire_time = (TextView) parent.findViewById(R.id.expire_time);
		  address = (TextView)parent. findViewById(R.id.address);
		  info = (TextView) parent.findViewById(R.id.info);
		  notice = (TextView) parent.findViewById(R.id.notice);
		  
		  source = (TextView) parent.findViewById(R.id.source);
		  value = (TextView) parent.findViewById(R.id.value);
		  phone = (TextView) parent.findViewById(R.id.phone);
		  rl_phone = (RelativeLayout) parent.findViewById(R.id.rl_phone);
		  rl_address = (RelativeLayout) parent.findViewById(R.id.rl_address);
		  layout_goods_detail = (LinearLayout) parent.findViewById(R.id.layout_goods_detail);
		  
		  
		  
		  if(timer!=null){timer.cancel();}
		  String shop_title = shop.getShop_title();
		  String strValue = shop.getValue();
		  String strPrice = shop.getPrice();
		  String strEnd_time = shop.getEnd_time();
		  String strDiscount = shop.getDiscount();
		  String strDistance = shop.getDistance();
		  String strInfo = shop_title+shop.getInfo();
		  String[] strDesc = strInfo.split("温馨提示：");
		  String strSource = shop.getSource();
		  String StrUse_num = shop.getUse_num();
		  String strPhone = shop.getNum();
		  
		  String strShop_address = shop.getShop_address();
		  String strShop_tel = shop.getShop_tel();
		  String strExpireTime = shop.getExpireTime();
		  cpsState = shop.getCpsState();
		  cid = shop.getId();
		  phoneNum  = strShop_tel;
		  final String photo_large = shop.getPhoto_large();
			if(isNull(photo_large)){
				String imageUrl = photo_large;
				String id = shop.getId();
				drawable=drawableCache.get(position);
				if(drawable!=null){
    				progressBar.setVisibility(View.GONE);
    				area_img.setVisibility(View.VISIBLE);
    				area_img.setMinimumHeight((int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, this.getResources().getDisplayMetrics()));
    				area_img.setImageDrawable(drawable);
				}else{
    				progressBar.setVisibility(View.GONE);
    				area_img.setVisibility(View.VISIBLE);
    				area_img.setMinimumHeight((int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, this.getResources().getDisplayMetrics()));
    				area_img.setImageResource(R.drawable.load_big);
					area_img.setMinimumHeight(300);
					sirectLoadImageFromUrl(imageUrl,position);	
				}
			}
			setOnClickListeners();
		  if(isNull(strDiscount)){
//					  discount.setText(getIdToString(R.string.discount)+strDiscount+getIdToString(R.string.fold));
			  
		  }
		  if(TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).size()>0){
			  if(text_center!=null){
					text_center.setText("团购详情("+(shopIndex+1)+"/"+TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).size()+")");
			  }
		  }
		if (isNull(strDesc[0])) {
			info.setText(strDesc[0]);
		}
		if(strDesc.length>1){
			if(isNull(strDesc[1])){
				  notice.setText(strDesc[1]);
			  }
		}else{
			findViewById(R.id.layout_notice).setVisibility(View.GONE);
		}
		  if(isNull(strSource)){
			  source.setText("【"+shop.getSource()+"】"
					  +"仅售"+new BigDecimal(Double.parseDouble(strPrice)).setScale(1,java.math.BigDecimal.ROUND_HALF_UP)+"元！");
		  }
		  if(isNull(phoneNum)){
			  phone.setText(phoneNum);
		  }else{
			  rl_phone.setVisibility(View.GONE);
		  }
		  if(isNull(strExpireTime)){
//				  expire_time.setText(strExpireTime);
		  }
		  if(isNull(strShop_address)){
				  address.setText(strShop_address);
		  }else{
			  rl_address.setVisibility(View.GONE);
		  }
		  if(isNull(strValue)&&!strValue.equals(getIdToString(R.string.No_))){
			  String str= strValue+getIdToString(R.string.yuan);
//			  SpannableString ss = new SpannableString(str);
//			  ss.setSpan(new StrikethroughSpan(), 3, str.length(),
//		                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
				  value.setText(str);
//				  value.setMovementMethod(LinkMovementMethod.getInstance());
		  }else{
				  value.setText(R.string.no_original_price);
		  }
		  if(isNull(strDiscount)){
			  discount.setText(strDiscount+getIdToString(R.string.fold));
		  }else{
			  discount.setText(getIdToString(R.string.No_discount));
		  }
		  
		  if(isNull(strValue)&&isNull(strPrice)&&!strValue.equals(getIdToString(R.string.No_))&&!strPrice.equals(getIdToString(R.string.No_))){
				  Double mSavePrice = Double.parseDouble(strValue)-Double.parseDouble(strPrice);
				  BigDecimal b = new BigDecimal(mSavePrice);  
				  double f1 = b.setScale(1,BigDecimal.ROUND_HALF_UP).doubleValue(); 
				  economize.setText(f1+getIdToString(R.string.yuan));
		    }else{
		    	   economize.setText(R.string.no_save);
			  }
		  if(isNull(strEnd_time)){
			  long time = Long.parseLong(strEnd_time);
			  if(time>0){
				  setExpireTime(time);
			  }else{
				  end_time.setText(R.string.has_expired);
			  }
		  }else{
				  end_time.setText(R.string.No_);
		  }
		  if(isNull(strPrice)&&!strPrice.equals(getIdToString(R.string.No_))){
				  buy_textview.setText("￥"+new BigDecimal(Double.parseDouble(strPrice)).setScale(1,java.math.BigDecimal.ROUND_HALF_UP)+"元");
			  }else{
					  buy_textview.setText(R.string.No_);
				  }
	}
	/**
	 * 剩余时间定时器
	 */
	public void setExpireTime(long t){
		if(timer!=null){
			timer.cancel();
		}
		  time = t;
		  TimerTask task = new TimerTask() { 
				 public void run() { 
					 time--;
					 timeHandler.sendEmptyMessage(0);
				} 
			}; 
	
		 timer = new Timer(); 
		 timer.schedule(task, 0,1000);	
	 }
	
	/**
	 * 计算剩余时间
	 */
	 public void getQuot(){
		 
		  long dd = 0;
		  long hh = 0;
		  long mm = 0;
		  long ss = 0;
		   dd = time / (60*60*24);
		   hh = time % (60*60*24) / (60*60);
		   mm = time % (60*60*24) % (60*60) / 60;
		   ss = time % (60*60*24) % (60*60) % 60;
		   String strTime = dd+"天"+hh+"时"+mm+"分"+ss+"秒";
		   end_time.setText(strTime); 
		  
		   
	 }
		 /**
		  * 判断是否为空
		  */
		public Boolean isNull(String str){
			if(str!=null&&!str.equals("")&&str!=""&&!str.equals("null")){
				return true;
			}
			return false;
		}
		public boolean onKeyDown(int keyCode, KeyEvent event) {
			
			
			if (keyCode == KeyEvent.KEYCODE_BACK) {
				if(timer!=null){
					timer.cancel();
				}
				if(ShopDetailActivity.mList.contains(this)){
					ShopDetailActivity.mList.remove(this);
				}
				this.finish();
				return true;
			}

			return false;
		}
		static class AlixOnCancelListener implements
				DialogInterface.OnCancelListener {
			Activity mcontext;
		
			AlixOnCancelListener(Activity context) {
				mcontext = context;
			}
		
			public void onCancel(DialogInterface dialog) {
				mcontext.onKeyDown(KeyEvent.KEYCODE_BACK, null);
			}
		}
		
	public void choose_share() {
		Dialog dialog = null;
		Builder b2 = new AlertDialog.Builder(this);
		b2.setTitle(R.string.spinner_share);
		b2.setItems(R.array.select_share, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if (which == 0) {
					UMSnsService.OauthCallbackListener listener_sina = new UMSnsService.OauthCallbackListener() {

						
						public void onError(UMSNSException arg0, SHARE_TO arg1) {
							Toast.makeText(TodayDetailActivity.this, "认证失败，请稍后再试", 1).show();
							arg0.printStackTrace();
						}

						
						public void onComplete(Bundle arg0, SHARE_TO arg1) {
							JSONObject info_sina = UMSnsService.getAccessToken(TodayDetailActivity.this, SHARE_TO.SINA);
							try {
								if (drawable != null) {
									BitmapDrawable bd = (BitmapDrawable) drawable;
									Bitmap bm = bd.getBitmap();
									ByteArrayOutputStream baos = new ByteArrayOutputStream();
									// 得到输出流
									bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
									// 转输入流
									InputStream isBm = new ByteArrayInputStream(baos.toByteArray());

									Bitmap bmp = BitmapFactory.decodeStream(isBm);
									ByteArrayOutputStream stream = new ByteArrayOutputStream();
									bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
									picture = stream.toByteArray();
									if (bmp != null && !bmp.isRecycled()) {
										bmp.recycle();
									}
									shareTitle = HomeActivity.dataSource.get(HomeActivity.dataType).get(shopIndex).getTitle();
									if(shareTitle.length()>35){
										shareTitle = shareTitle.substring(0, 35);
									}
									UMSnsService.shareToSina(TodayDetailActivity.this, picture, "我刚用@手机买团购  入手了#"+shareTitle+"#现在分享还有优惠券领，真开心http://www.lookoo.cn/pages/tuangou", null);
								} else {

									// if(isFromShoppings){
									shareTitle = TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).get(shopIndex).getTitle();
									if(shareTitle.length()>35){
										shareTitle = shareTitle.substring(0, 35);
									}
									// }else{
									// shareTitle = mGoodsDetail.getTitle();
									// }
									UMSnsService.shareToSina(TodayDetailActivity.this, "我刚用@手机买团购  入手了#"+shareTitle+"#现在分享还有优惠券领，真开心http://www.lookoo.cn/pages/tuangou", null);
								}

							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					};
					UMSnsService.oauthSina(TodayDetailActivity.this, listener_sina);

				} else if (which == 1) {
					UMSnsService.OauthCallbackListener listener_qq = new UMSnsService.OauthCallbackListener() {

						
						public void onError(UMSNSException arg0, SHARE_TO arg1) {
							Toast.makeText(TodayDetailActivity.this, "认证失败，请稍后再试", 1).show();
							arg0.printStackTrace();
						}

						
						public void onComplete(Bundle arg0, SHARE_TO arg1) {
							JSONObject info_qq = UMSnsService.getAccessToken(TodayDetailActivity.this, SHARE_TO.TENC);

							try {
								if (drawable != null) {
									BitmapDrawable bd = (BitmapDrawable) drawable;
									Bitmap bm = bd.getBitmap();
									ByteArrayOutputStream baos = new ByteArrayOutputStream();
									// 得到输出流
									bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
									// 转输入流
									InputStream isBm = new ByteArrayInputStream(baos.toByteArray());

									Bitmap bmp = BitmapFactory.decodeStream(isBm);
									ByteArrayOutputStream stream = new ByteArrayOutputStream();
									bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
									picture = stream.toByteArray();
									if (bmp != null && !bmp.isRecycled()) {
										bmp.recycle();
									}
									shareTitle = TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).get(shopIndex).getTitle();
									if(shareTitle.length()>35){
										shareTitle = shareTitle.substring(0, 35);
									}
									UMSnsService.shareToTenc(TodayDetailActivity.this, picture, "我刚用@手机买团购  入手了#"+shareTitle+"#现在分享还有优惠券领，真开心http://www.lookoo.cn/pages/tuangou", null);
								} else {

									// if(isFromShoppings){
									// shareTitle
									// =ShoppingsActivity.main_shopping.get(ShoppingsActivity.type).get(shopIndex).getTitle();
									// }else{
									// shareTitle = mGoodsDetail.getTitle();
									// }
									shareTitle = TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).get(shopIndex).getTitle();
									if(shareTitle.length()>35){
										shareTitle = shareTitle.substring(0, 35);
									}
									UMSnsService.shareToTenc(TodayDetailActivity.this, "我刚用@手机买团购  入手了#"+shareTitle+"#现在分享还有优惠券领，真开心http://www.lookoo.cn/pages/tuangou", null);
								}

							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					};
					UMSnsService.oauthTenc(TodayDetailActivity.this, listener_qq);
				} else if (which == 2) {
					UMSnsService.OauthCallbackListener listener_renren = new UMSnsService.OauthCallbackListener() {

						
						public void onError(UMSNSException arg0, SHARE_TO arg1) {
							Toast.makeText(TodayDetailActivity.this, "认证失败，请稍后再试", 1).show();
							arg0.printStackTrace();
						}

						
						public void onComplete(Bundle arg0, SHARE_TO arg1) {
							JSONObject info_renren = UMSnsService.getAccessToken(TodayDetailActivity.this, SHARE_TO.RENR);

							try {
								if (drawable != null) {
									BitmapDrawable bd = (BitmapDrawable) drawable;
									Bitmap bm = bd.getBitmap();
									ByteArrayOutputStream baos = new ByteArrayOutputStream();
									// 得到输出流
									bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
									// 转输入流
									InputStream isBm = new ByteArrayInputStream(baos.toByteArray());

									Bitmap bmp = BitmapFactory.decodeStream(isBm);
									ByteArrayOutputStream stream = new ByteArrayOutputStream();
									bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
									picture = stream.toByteArray();
									if (bmp != null && !bmp.isRecycled()) {
										bmp.recycle();
									}
									shareTitle = TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).get(shopIndex).getTitle();
									if(shareTitle.length()>35){
										shareTitle = shareTitle.substring(0, 35);
									}
									UMSnsService.shareToRenr(TodayDetailActivity.this, picture, "我刚用@手机买团购  入手了#"+shareTitle+"#现在分享还有优惠券领，真开心http://www.lookoo.cn/pages/tuangou", null);
								} else {

									// if(isFromShoppings){
									// shareTitle
									// =ShoppingsActivity.main_shopping.get(ShoppingsActivity.type).get(shopIndex).getTitle();
									// }else{
									// shareTitle = mGoodsDetail.getTitle();
									// }
									shareTitle = TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).get(shopIndex).getTitle();
									if(shareTitle.length()>35){
										shareTitle = shareTitle.substring(0, 35);
									}
									UMSnsService.shareToRenr(TodayDetailActivity.this, "我刚用@手机买团购  入手了#"+shareTitle+"#现在分享还有优惠券领，真开心http://www.lookoo.cn/pages/tuangou", null);
								}

							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					};
					UMSnsService.oauthRenr(TodayDetailActivity.this, listener_renren);
				} else if (which == 3) {

					/*
					 * 下列参数用于修改应用信息 Constant.packageName Kaixin.API_KEY
					 * Kaixin.SECRET_KEY Kaixin.KX_AUTHORIZE_CALLBACK_URL=
					 * "lookooshop2.0://PostRecordActivity"
					 */

					Kaixin.API_KEY = "543188970332f2e15eeaa7a75496ad1b";
					Kaixin.SECRET_KEY = "d69f1f232a0096dbc75557116b09ef02";

					ShopDetailActivity.shareShopImage= TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).get(shopIndex).getPhoto_large();
					ShopDetailActivity.shareShopid= TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).get(shopIndex).getId();
					Constant.packageName = new String("");
					Kaixin kaixin = Kaixin.getInstance();
					kaixin.loadStorage(TodayDetailActivity.this);
					if (kaixin.isSessionValid()) {
						Intent result = new Intent(TodayDetailActivity.this, OAuthKaixinActivity.class);

						result.putExtra("login", "kaixin");
						startActivity(result);
					} else {
						String[] permissions = { "basic", "create_records" };
						kaixin.authorize(TodayDetailActivity.this, permissions, null);
					}
				}

			}
		});
		dialog = b2.create();
		dialog.show();

	}
		
	     //直接加载图片
	 public  void sirectLoadImageFromUrl(final String url, final int shopIndex) {
		 	String filePath;
		 	filePath = "/sdcard/tuangou/"+TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).get(shopIndex).getId()+"large.jpg";
	 		File file=new File(filePath);
			if(file.exists()){
				Drawable drawable=Drawable.createFromPath(filePath);
				if(drawable!=null){
					drawableCache.put(shopIndex, drawable);
					waitHander.sendEmptyMessage(0); 
				}else{
					file.delete();
				}
		} else {
			executorService.execute(new Thread() {
				InputStream is = null;
				Drawable drawable = null;

				
				public void run() {
					// TODO Auto-generated method stub
					try {
						HttpURLConnection conn = Util.getHttpURLConnection(url);
						conn.setDoInput(true);
						if (conn.getResponseCode() == 200) {
							is = conn.getInputStream();
							int contentLength = conn.getContentLength();
							if (is != null) {
								Bitmap bitmap = BitmapFactory.decodeStream(is);
								drawable = new BitmapDrawable(bitmap);
								if (drawable != null && contentLength > 4) {
									drawableCache.put(shopIndex, drawable);
									waitHander.sendEmptyMessage(0);
									try {
										String filePath;
										filePath = "/sdcard/tuangou/"
												+ TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).get(shopIndex).getId()
												+ "large.jpg";
										File fp = new File("/sdcard/tuangou");
										File file = new File("/sdcard/tuangou/.nomedia");
										if (!fp.exists()) {
											fp.mkdir();
											if ((!file.exists())) {
												file.createNewFile();
											}
										} else {
											File f = new File(filePath);
											f.createNewFile();
											FileOutputStream fos = new FileOutputStream(f);
											bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
											fos.flush();
											fos.close();
											// imageFileSave.imageSave(imageService,new
											// Image(id, filePath));
										}
									} catch (Exception e) {
										e.printStackTrace();
									}

									try {
										String filePath;
										filePath = "/sdcard/tuangou/"
												+ TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).get(shopIndex).getId()
												+ "large.jpg";

										File fp = new File("/sdcard/tuangou");
										File file = new File("/sdcard/tuangou/.nomedia");
										if (!fp.exists()) {
											fp.mkdir();
											if ((!file.exists())) {
												file.createNewFile();
											}
										} else {
											File f = new File(filePath);
											f.createNewFile();
											FileOutputStream fos = new FileOutputStream(f);
											bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
											fos.flush();
											fos.close();
										}
									} catch (Exception e) {
										e.printStackTrace();
									}
								}
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
						//							 
					}
				}
			});
		}
	}
	 	public boolean getNetConnectState(Context context) {
			boolean netConnect = false;
			ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo info = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			NetworkInfo infoM = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			if (info.isConnected() || infoM.isConnected()) {
				netConnect = true;
			}
			return netConnect;
		}
	 	private class PageAdapter extends PagerAdapter
		{
			// 销毁arg1位置的界面
			
			public void destroyItem(View arg0, int arg1, Object arg2)
			{
				((ViewPager) arg0).removeView(mListViews.get(arg1%8));
			}
			// 获取当前窗体界面数
			
			public int getCount()
			{
				return TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).size();
			}

			// 初始化arg0位置的界面
			
			public Object instantiateItem(View arg0, int arg1)
			{
				((ViewPager) arg0).addView(mListViews.get(arg1%8), 0);
				return mListViews.get(arg1%8);
			}

			// 判断是否由对象生成界面
			
			public boolean isViewFromObject(View arg0, Object arg1)
			{
				return arg0 == (arg1);
			}
		}
	 	
	 	
		private void getShops(){
			if(TodayBuyActivity.recordError.contains(TodayBuyActivity.dataType+"")){
				TodayBuyActivity.recordError.remove(TodayBuyActivity.dataType+"");
				TodayBuyActivity.isload[TodayBuyActivity.dataType]=true;
			} 
			if(TodayBuyActivity.isload[TodayBuyActivity.dataType]){
	    		TodayBuyActivity.isload[TodayBuyActivity.dataType] = false;
	    		//显示加载中
	    		showProgress();
			if (getNetConnectState(TodayDetailActivity.this)) {
				executorService.execute(new Thread() {
					public void run() {
						Boolean temp = false;
						MResult mResult;

						mResult = MSystem.getShopsFromToday(TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType),
								TodayBuyActivity.cat, TodayBuyActivity.dataPage[TodayBuyActivity.dataType], TodayBuyActivity.dataType,
								TodayBuyActivity.order);

						if (TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).size() == 0) {
							TodayBuyActivity.dataPage[TodayBuyActivity.dataType] = 1;
						} else {
							TodayBuyActivity.dataPage[TodayBuyActivity.dataType] = TodayBuyActivity.dataPage[TodayBuyActivity.dataType] + 1;
						}

						if (mResult != null) {
							if (mResult.isSuccess()) {
								waitHander.sendEmptyMessage(10);
								temp = mResult.isPage();
								if (!mResult.isPage()) {
									waitHander.sendEmptyMessage(102);
									if (TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).size() > 8) {
										MainTabActivity.showHander.sendEmptyMessage(102);
									}
								}
							} else {
								waitHander.sendEmptyMessage(104);
							}
						} else {

							TodayBuyActivity.dataPage[TodayBuyActivity.dataType] = TodayBuyActivity.dataPage[TodayBuyActivity.dataType] - 1;
							TodayBuyActivity.recordError.add(TodayBuyActivity.dataType + "");
							waitHander.sendEmptyMessage(103);
						}
						TodayBuyActivity.isload[TodayBuyActivity.dataType] = temp;
						hideProgress();
					}
				});
			}else{
						hideProgress();
						TodayBuyActivity.recordError.add(TodayBuyActivity.dataType+"");
						waitHander.sendEmptyMessage(103);
				}	
	    	} 
		}
		protected void showProgress() {
			this.runOnUiThread(new Runnable() {
				public void run() {	
					if(mProgress==null){
						mProgress = new ProgressDialog(TodayDetailActivity.this);
						mProgress.requestWindowFeature(Window.FEATURE_NO_TITLE);
						mProgress.setMessage("数据加载中,请稍后...");
						
					}
					mProgress.show();
					
					
				}
			});
		}

		/**
		 * 取消等待框
		 */
		protected void hideProgress() {
			
			this.runOnUiThread(new Runnable() {
				public void run() {
					if (mProgress != null) {
						mProgress.dismiss();
					}
				}
			});
		}
}
